package com.bawei.module_live.player

import android.content.Context
import android.media.AudioFocusRequest
import android.util.Log
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import com.bawei.module_live.version1.VideoEntityItem

class ExoPlayerManager(private val context: Context) {
    private val appContext: Context = context.applicationContext
    private var audioFocusRequest: AudioFocusRequest? = null
    companion object {
        private const val TAG = "ExoPlayerManager"
        
        // 测试视频 URL
        private val TEST_VIDEO_URLS = listOf(
            "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
            "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4",
            "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"
        )
    }
    
    private var exoPlayer: ExoPlayer? = null
    private var currentVideoUrl: String? = null
    private var currentPosition = -1
    private val audioFocusManager: AudioFocusManager = AudioFocusManager(appContext)
    private var pendingSeekTo: Long? = null
    
    init {
        initializePlayer()
    }
    
    private fun initializePlayer() {
        try {
            exoPlayer = ExoPlayer.Builder(appContext).build().apply {
                repeatMode = Player.REPEAT_MODE_ONE // 循环播放
                addListener(object : Player.Listener {
                    override fun onPlaybackStateChanged(playbackState: Int) {
                        when (playbackState) {
                            Player.STATE_READY -> {
                                Log.d(TAG, "视频准备就绪，开始播放")
                                play() // 自动开始播放
                                pendingSeekTo?.let {
                                    seekTo(it)
                                    pendingSeekTo = null
                                }
                            }
                            Player.STATE_BUFFERING -> {
                                Log.d(TAG, "视频缓冲中")
                            }
                            Player.STATE_ENDED -> {
                                Log.d(TAG, "视频播放结束")
                            }
                            Player.STATE_IDLE -> {
                                Log.d(TAG, "视频播放器空闲")
                            }
                        }
                    }
                    
                    override fun onPlayerError(error: androidx.media3.common.PlaybackException) {
                        Log.e(TAG, "播放错误: ${error.message}")
                        Log.e(TAG, "错误原因: ${error.cause}")
                        Log.e(TAG, "错误代码: ${error.errorCode}")
                    }
                    
                    override fun onIsPlayingChanged(isPlaying: Boolean) {
                        Log.d(TAG, "播放状态变化: $isPlaying")
                    }
                })
            }
            Log.d(TAG, "ExoPlayer 初始化成功")
        } catch (e: Exception) {
            Log.e(TAG, "初始化播放器失败: ${e.message}")
        }
    }
    
    fun setPlayerView(playerView: PlayerView) {
        try {
            exoPlayer?.let { player ->
                playerView.player = player
                Log.d(TAG, "设置播放器视图成功")
            }
        } catch (e: Exception) {
            Log.e(TAG, "设置播放器视图失败: ${e.message}")
        }
    }
    
    fun playVideo(video: VideoEntityItem, position: Int, seekToMs: Long? = null) {
        try {
            Log.d(TAG, "准备播放视频: ${video.title}")
            Log.d(TAG, "视频路径: ${video.videopath}")

            var videoUrl = video.videopath.takeIf { !it.isNullOrEmpty() }

            // 如果视频 URL 为空或无效，使用测试视频
            if (videoUrl.isNullOrEmpty() || videoUrl == "null") {
                Log.w(TAG, "视频URL为空或无效，使用测试视频")
                videoUrl = TEST_VIDEO_URLS.getOrNull(position % TEST_VIDEO_URLS.size)
                Log.d(TAG, "使用测试视频URL: $videoUrl")
            }

            if (videoUrl.isNullOrEmpty()) {
                Log.w(TAG, "无法获取有效的视频URL")
                return
            }

            // 如果是同一个视频，不需要重新加载
            if (videoUrl == currentVideoUrl && position == currentPosition) {
                if (exoPlayer?.isPlaying == false) {
                    // 请求音频焦点
                    audioFocusManager.requestAudioFocus { hasFocus ->
                        // 无论是否获得音频焦点都播放
                        exoPlayer?.play()
                        Log.d(TAG, "继续播放当前视频（无论音频焦点）")
                    }
                }
                // 新增：如果需要seekTo，直接seek
                seekToMs?.let { seekTo(it) }
                return

            }

            // 停止当前播放
            stopPlayback()

            // 记录待seek进度
            pendingSeekTo = seekToMs
            audioFocusManager.requestAudioFocus { hasFocus ->
                // 无论是否获得音频焦点都播放
                try {
                    Log.d(TAG, "设置媒体项: $videoUrl")
                    val mediaItem = MediaItem.fromUri(videoUrl)
                    exoPlayer?.setMediaItem(mediaItem)
                    exoPlayer?.prepare()
                    currentVideoUrl = videoUrl
                    currentPosition = position
                    Log.d(TAG, "开始播放视频: ${video.title} at position: $position")
                    Log.d(TAG, "视频URL: $videoUrl")
                    if (!hasFocus) {
                        Log.w(TAG, "未获得音频焦点，但仍然尝试播放视频")
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "设置媒体项失败: ${e.message}")
                    e.printStackTrace()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "播放视频失败: ${e.message}")
            e.printStackTrace()
        }
    }
    
    fun pausePlayback() {
        try {
            exoPlayer?.pause()
            Log.d(TAG, "暂停视频播放")
        } catch (e: Exception) {
            Log.e(TAG, "暂停播放失败: ${e.message}")
        }
    }
    
    fun stopPlayback() {
        try {
            exoPlayer?.stop()
            Log.d(TAG, "停止视频播放")
        } catch (e: Exception) {
            Log.e(TAG, "停止播放失败: ${e.message}")
        }
    }
    
    fun release() {
        try {
            // 1. 先释放音频焦点（确保顺序）
            audioFocusManager.abandonAudioFocus() // 确保内部完全释放回调
            audioFocusRequest = null // 显式置空

            // 2. 停止并释放播放器
            stopPlayback()
            exoPlayer?.release()
            exoPlayer = null

            // 3. 清理其他引用
            currentVideoUrl = null
            currentPosition = -1
//            // 释放音频焦点
//            audioFocusRequest?.let { request ->
//                val audioManager = context.getSystemService(AUDIO_SERVICE) as AudioManager
//                audioManager.abandonAudioFocusRequest(request)
//            }
//            stopPlayback()
//            audioFocusManager.abandonAudioFocus()
//            exoPlayer?.release()
//            exoPlayer = null
//            currentVideoUrl = null
//            currentPosition = -1
            Log.d(TAG, "释放播放器资源")
        } catch (e: Exception) {
            Log.e(TAG, "释放播放器失败: ${e.message}")
        }
    }
    
    fun isPlaying(): Boolean {
        return exoPlayer?.isPlaying == true
    }
    
    fun getCurrentPosition(): Int {
        return currentPosition
    }
    
    fun getCurrentVideoUrl(): String? {
        return currentVideoUrl
    }
    
    fun seekTo(positionMs: Long) {
        exoPlayer?.seekTo(positionMs)
    }
} 